<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>学院管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">新增学院</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索条件 -->
    <el-form :model="searchForm" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="学院名称">
            <el-input v-model="searchForm.name" placeholder="请输入学院名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 学院列表 -->
    <el-table :data="collegeList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="学院名称" width="200" />
      <el-table-column prop="code" label="学院代码" width="120" />
      <el-table-column prop="description" label="描述" width="200" />
      <el-table-column prop="majorCount" label="专业数量" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="学院名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="学院代码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 学院列表
const collegeList = ref([])

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入学院名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入学院代码', trigger: 'blur' }]
}

const formRef = ref()

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 获取学院列表
const fetchColleges = async () => {
  loading.value = true
  try {
    // 添加分页参数和搜索参数
    const params = new URLSearchParams();
    params.append('page', pagination.currentPage - 1); // 后端分页从0开始
    params.append('size', pagination.pageSize);
    
    // 添加搜索参数
    if (searchForm.name) {
      params.append('name', searchForm.name);
    }
    if (searchForm.status) {
      params.append('status', searchForm.status);
    }
    
    const response = await axios.get(`http://localhost:8080/api/colleges?${params.toString()}`);
    collegeList.value = response.data.content.map(college => ({
      ...college,
      createTime: formatDate(college.createdAt)
    }))
    pagination.total = response.data.totalElements
  } catch (error) {
    console.error('获取学院列表失败:', error)
    ElMessage.error('获取学院列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  console.log('搜索:', searchForm)
  // 重置到第一页
  pagination.currentPage = 1
  await fetchColleges()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  // 重置到第一页
  pagination.currentPage = 1
  fetchColleges()
}

// 刷新
const handleRefresh = () => {
  fetchColleges()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增学院'
  isEdit.value = false
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 'active' : ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑学院'
  isEdit.value = true
  // 填充表单数据
  Object.keys(form).forEach(key => {
    form[key] = row[key] !== undefined ? row[key] : (key === 'status' ? 'active' : '')
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    // 先获取学院详情，检查是否有关联的专业
    try {
      const response = await axios.get(`http://localhost:8080/api/colleges/${row.id}`);
      const collegeDetail = response.data;
      
      // 检查学院是否有关联的专业（这里假设后端会在返回的数据中包含专业数量信息）
      // 如果后端没有提供专业数量信息，我们可以通过其他方式检查
      if (collegeDetail.majorCount !== undefined && collegeDetail.majorCount > 0) {
        ElMessageBox.confirm(
          `学院 ${row.name} 下还有 ${collegeDetail.majorCount} 个专业，无法直接删除。`,
          '无法删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(() => {});
        return;
      }
    } catch (detailError) {
      // 如果获取详情失败，继续执行删除操作
      console.warn('获取学院详情失败:', detailError);
    }
    
    await ElMessageBox.confirm(
      `确定要删除学院 ${row.name} 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除
    const response = await axios.delete(`http://localhost:8080/api/colleges/${row.id}`)
    
    // 检查后端返回的响应
    if (response.data) {
      ElMessage.success(response.data)
    } else {
      ElMessage.success('删除成功')
    }
    
    fetchColleges() // 重新加载数据
  } catch (error) {
    if (error.response && error.response.status === 400) {
      // 处理后端返回的错误信息
      ElMessage.error(error.response.data)
    } else if (error !== 'cancel') {
      console.error('删除学院失败:', error)
      ElMessage.error('删除学院失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑操作
          await axios.put(`http://localhost:8080/api/colleges/${form.id}`, {
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status
          })
          ElMessage.success('编辑成功')
        } else {
          // 新增操作
          await axios.post('http://localhost:8080/api/colleges', {
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status
          })
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        // 重置到第一页并重新加载数据
        pagination.currentPage = 1
        fetchColleges()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 重置到第一页
  pagination.currentPage = 1
  fetchColleges()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchColleges()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchColleges()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>